package com.kdx.wallet.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kdx.wallet.entity.Prod;
import com.kdx.wallet.entity.Record;
import com.kdx.wallet.entity.User;
import com.kdx.wallet.entity.Wallet;
import com.kdx.wallet.mapper.RecordMapper;
import com.kdx.wallet.mapper.UserMapper;
import com.kdx.wallet.mapper.WalletMapper;
import com.kdx.wallet.service.WalletService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.concurrent.Executors;

@Service
public class WalletServiceImpl extends ServiceImpl<WalletMapper, Wallet> implements WalletService {
    @Resource
    private RecordMapper recordMapper;

    /**
     * 根据用户id查余额
     */
    @Override
    public Wallet getAmount(Integer userId) {
        QueryWrapper<Wallet> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);

        return getOne(wrapper);
    }

    /**
     * 用户充值
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean recharge(Integer userId, Double amount) {
        Wallet wallet = getAmount(userId);

        wallet.setBalance(wallet.getBalance() + amount);
        boolean b = updateById(wallet);

        Record record = new Record();
        record.setAmount(amount);
        record.setType(3);
        record.setUserId(wallet.getUserId());
        int insert = recordMapper.insert(record);
        return b && (insert > 0);
    }

    /**
     * 用户提现
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean withdraw(Integer userId, Double amount) {
        Wallet wallet = getAmount(userId);

        wallet.setBalance(wallet.getBalance() - amount);
        boolean b = updateById(wallet);

        Record record = new Record();
        record.setAmount(amount);
        record.setType(4);
        record.setUserId(wallet.getUserId());
        int insert = recordMapper.insert(record);
        return b && (insert > 0);
    }
}
